package com.zxjbyte.yiyi.framework.common.core.okhttp.callback;

import com.zxjbyte.yiyi.framework.common.exception.ServiceException;
import lombok.Data;
import okhttp3.Call;
import okhttp3.Request;

import java.util.List;
import java.util.Map;

/**
 * 失败回调信息上下文
 *
 * @Author zhangxingjia
 * @Date 2024/4/28 14:55
 * @Version: 1.0
 */
@Data
public class FailureContext {
    /**
     * 失败回调
     */
    private Call call;

    /**
     * 导致故障的异常
     */
    private Exception exception;
    /**
     * 响应的状态代码（如果可用），否则为0
     */
    private int statusCode;
    /**
     * 响应的标头（如果可用），否则将为null
     */
    private Map<String, List<String>> responseHeaders;

    public static FailureContext of(Call call, Exception e){
        FailureContext context = new FailureContext();
        context.setCall(call);
        context.setException(e);
        return context;
    }

    public static FailureContext of(Call call, Exception e, int statusCode, Map<String, List<String>> responseHeaders){
        FailureContext context = new FailureContext();
        context.setCall(call);
        context.setException(e);
        context.setStatusCode(statusCode);
        context.setResponseHeaders(responseHeaders);
        return context;
    }

    /**
     * 封装业务异常
     * @return
     */
    public ServiceException serviceException(){
        if(exception instanceof ServiceException){
            return (ServiceException) exception;
        }
        return new ServiceException(exception);
    }

    /**
     * This is Request
     * @return
     */
    public Request request(){
        return call.request();
    }

}
